package controller

import (
	"fmt"
	"server/internal/dao"
	"server/internal/util"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func HandlerCreateIssue(c *gin.Context) {
	issue, err := dao.CreateIssue()

	if err != nil {
		logrus.Debug("create new issue failed")
		util.Errs(c, "create new issue failed")
		return
	}

	util.RespSuccess(c, struct{ ID int }{ID: int(issue.ID)}, util.RequestSuccess)
}

func HandlerDeleteIssue(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		logrus.Debug("delete issue id can not be empty")
		util.Errs(c, "delete issue id can not be empty")
		return
	}

	issue, err := dao.SearchIssueByID(id)
	if err != nil {
		logrus.Debugf("issue id: %s does not exist", id)
		util.Errs(c, fmt.Sprintf("issue id: %s does not exist", id))
		return
	}

	if err = dao.DeleteIssue(issue); err != nil {
		logrus.Debugf("delete issue id: %s failed", id)
		util.Errs(c, fmt.Sprintf("delete issue id: %s failed", id))
		return
	}

	util.RespSuccessWithoutData(c, util.RequestSuccess)
}

func HandlerGetIssue(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		logrus.Debug("get issue id can not be empty")
		util.Errs(c, "get issue id can not be empty")
		return
	}

	issue, err := dao.SearchIssueByID(id)
	if err != nil {
		logrus.Debug(err)
		logrus.Debugf("get issue id: %s does not exist", id)
		util.Errs(c, fmt.Sprintf("get issue id: %s does not exist", id))
		return
	}

	util.RespSuccess(c, issue, util.RequestSuccess)
}

func HandlerGetIssues(c *gin.Context) {

	issues, err := dao.GetIssues()
	if err != nil {
		logrus.Debug(err)
		logrus.Debug("get issues failed")
		util.Errs(c, "get issues failed")
		return
	}

	util.RespSuccess(c, issues, util.RequestSuccess)
}

func HandlerPublishIssue(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		logrus.Debug("publish issue id can not be empty")
		util.Errs(c, "publish issue id can not be empty")
		return
	}

	issue, err := dao.SearchIssueByID(id)
	if err != nil {
		logrus.Debugf("publish issue id: %s does not exist", id)
		util.Errs(c, fmt.Sprintf("publish issue id: %s does not exist", id))
		return
	}

	if err = dao.PublishIssue(issue); err != nil {
		logrus.Debugf("publish issue id: %s failed", id)
		util.Errs(c, fmt.Sprintf("publish issue id: %s failed", id))
		return
	}

	util.RespSuccessWithoutData(c, util.RequestSuccess)
}

func HandlerGetLatestIssue(c *gin.Context) {
	issues, err := dao.GetLatestIssues()
	if err != nil {
		logrus.Debug(err)
		logrus.Debug("get issues failed")
		util.Errs(c, "get issues failed")
		return
	}
	max := 0
	maxID := -1
	for idx, issue := range *issues {
		if int(issue.ID) > maxID {
			max = idx
			maxID = int(issue.ID)
		}
	}

	util.RespSuccess(c, (*issues)[max], util.RequestSuccess)
}
